<template>
    <div style="border:1px solid rgb(202, 202, 202);margin:0 5px">
        <div style="padding:5px;border-bottom:1px solid rgb(202, 202, 202);font-weight:700;height:43px;line-height:31px">
            <!-- <span v-if="type == 'history' && type != 'detail'" style="margin-right:10px">
                同步时间：
                <el-date-picker v-model="historyParam.date" size="mini" type="date" placeholder="选择日期"> </el-date-picker>
                <el-input v-model="historyParam.idName" size="mini" style="width:220px;margin:0 10px" placeholder="编号/名称"></el-input>
                <el-button type="primary" size="mini" @click="query">查询</el-button>
            </span> -->
            <span v-if="type != 'detail' && tranParams.entryETL">
                导数结果：<span style="color:red"
                    >{{ typeof syncResult.etlResult === 'boolean' ? (syncResult.etlResult ? '成功' : '失败') : null }} &nbsp;&nbsp;
                </span>
            </span>
            同步数量：<span style="color:red">{{ amount.totalAmount }} &nbsp;&nbsp;</span> 成功数量：<span style="color:red"
                >{{ amount.successAmount }} &nbsp;&nbsp;</span
            >
            失败数量：<span style="color:red">{{ amount.errorAmount }}</span>
        </div>
        <el-row>
            <el-col :span="12" class="content" :class="type == 'detail' ? 'inner-content' : 'outer-content'">
                <div class="content-header">{{ syncCategory == '1' ? '成功条目：' : '成功维度：' }}</div>
                <RiskTable :msg="successMsg" class="table-height" @handleFilter="handleFilterChange($event, 'success')"></RiskTable>
                <RiskPagination :paging="pagingSuccess" @page-change="pageChange('success', $event)"></RiskPagination>
            </el-col>
            <el-col :span="12" class="content" :class="type == 'detail' ? 'inner-content' : 'outer-content'">
                <div class="content-header">{{ syncCategory == '1' ? '失败条目：' : '失败维度：' }}</div>
                <RiskTable :msg="errorMsg" class="table-height" @handleFilter="handleFilterChange($event, 'error')"></RiskTable>
                <RiskPagination :paging="pagingError" @page-change="pageChange('error', $event)"></RiskPagination>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTable from '@/common/components/risk-table.vue';
import { getSyncDataDetailItem, getSyncDataList } from '@/pages/system-maintence/api';
import { dateFormat, timeFormat } from '@/utils/tools';
import { Component, Prop, Vue } from 'vue-property-decorator';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'CurrentSyncContent',
    components: {
        RiskTable,
        RiskPagination,
    },
})
export default class CurrentSyncContent extends Vue {
    @Prop({ default: 'current' }) type: string;
    @Prop() tranParams: any;
    @Prop() outerAmount: any;
    pagingError = {
        total: 0,
        currentPage: 1,
        pageSize: 25,
    };
    pagingSuccess = {
        total: 0,
        currentPage: 1,
        pageSize: 25,
    };

    searchParams: any = {
        code: '',
        codeAndName: '',
        name: '',
        batchId: '',
        isNew: '',
        syncCategory: '1', // 1 条目同步 0 动态维度同步
        syncStatus: '', // 1 成功  0 失败
    };

    // historyParam: any = {
    //     date: '',
    //     idName: '',
    // };
    // 数量
    amount = {
        totalAmount: 0,
        successAmount: 0,
        errorAmount: 0,
    };
    showHeight: string = 'calc(100vh - 250px)';
    synEventShowObj: any = {
        '0': '增量手动',
        '1': '全量手动',
        '2': '按类别手动',
        '3': '单个手动',
        '4': '监听自动',
        '5': '初始化自动',
    };
    // 成功条目
    columns = [
        {
            name: '编号',
            val: 'code',
            filters: [{ data: '' }],
            search: true,
        },
        {
            name: '名称',
            val: 'name',
            type: 'func',
            funcBody: (value, row) => row.name || row.paramErrorMessage || row.errorMsg,
            filters: [{ data: '' }],
            search: true,
        },
        { name: '同步类型', val: 'synEventShow', type: 'status', statusKV: this.synEventShowObj },
        {
            name: '同步时间',
            val: 'dtCtTime',
            type: 'func',
            funcBody: (value, row) => dateFormat(row.dtCtDate) + ' ' + timeFormat(row.dtCtTime, false, 'HH:mm'),
        },
    ];

    successMsg: any = {
        returnData: {},
        dataKey: 'list',
        title: this.columns,
        checked: { on: false, option: false },
        hidePage: true,
    };

    errorMsg: any = {
        returnData: {},
        dataKey: 'list',
        title: this.columns,
        checked: { on: false, option: false },
        hidePage: true,
    };
    // 失败条目
    private errorDataSource: any = [];
    private errorDataSourceList: any = [];

    // private errorMessage: string = '';

    private successPage: pages = {
        currentPage: 1,
        pageSize: 50,
    };
    private errorPage: pages = {
        currentPage: 1,
        pageSize: 50,
    };
    private syncResult: any = {
        totalAmount: '',
        successAmount: '',
        successEntry: '',
        errorAmount: '',
        errorEntry: '',
        errorMsg: '',
        etlResult: '',
    };
    private syncLoading: boolean = false;
    batchId: string = '';
    syncCategory: string = '1';
    // 同步(id,同步状态:0 失败  1 成功,needError:是否查询错误,类型: 1 条目同步 0 动态维度同步)
    async handleClickSync(syncStatus: any, needError = false, syncCategory: string, operateType?: any, batchId?: any) {
        batchId && (this.amount = this.outerAmount);

        if (this.type == 'current') {
            batchId = batchId || (await this.getBatchId(syncCategory));
        } else {
            // 历史一直用默认值
            batchId = batchId || this.batchId;
        }
        this.batchId = batchId;
        needError && this.handleClickSync('0', false, syncCategory, 'autoRefresh', this.batchId);
        if (!batchId && batchId !== 0) {
            return;
        }
        let syncParam = JSON.parse(JSON.stringify(this.searchParams));
        syncParam.batchId = batchId;
        this.syncCategory = syncCategory;
        this.syncLoading = true;
        syncParam.isNew = this.type == 'current' ? '1' : '0'; // 0 历史 1最新
        syncParam.syncStatus = syncStatus;
        syncParam.syncCategory = syncCategory;
        // 0 失败  1 成功
        if (syncStatus == '0') {
            syncParam.paging = this.pagingError;
            syncParam.code = this.codeFilter[0] || '';
            syncParam.name = this.nameFilter[0] || '';
        } else {
            syncParam.paging = this.pagingSuccess;
            syncParam.code = this.codeFilter[1] || '';
            syncParam.name = this.nameFilter[1] || '';
        }

        getSyncDataDetailItem({ ...syncParam }, operateType).then(
            (res: any) => {
                if (res) {
                    if (syncStatus == '0') {
                        this.pagingError.total = res.total;
                        this.$set(this.errorMsg.returnData, 'list', res.list);
                    } else if (syncStatus == '1') {
                        this.pagingSuccess.total = res.total;
                        this.$set(this.successMsg.returnData, 'list', res.list);
                    }
                }
                this.syncLoading = false;
            },
            () => {
                this.cleanLastResult();
                this.syncLoading = false;
            }
        );
    }

    //  同步之前清空 之前的的同步结果
    private cleanLastResult(): void {
        // todo
        this.syncResult = {
            totalAmount: '',
            successAmount: '',
            successEntry: '',
            errorAmount: '',
            errorEntry: '',
            errorMsg: '',
            etlResult: '',
        };
        this.$set(this.successMsg.returnData, 'list', []);
        this.$set(this.errorMsg.returnData, 'list', []);
    }

    // 前端分页(条目初始化)
    pageChange(type: string, data?: any) {
        if (type == 'success') {
            this.handleClickSync('1', false, this.syncCategory);
        } else {
            this.handleClickSync('0', false, this.syncCategory);
        }
    }

    // 获取batchId
    getBatchId(syncCategory) {
        return new Promise((resolve, reject) => {
            getSyncDataList({ syncCategory: syncCategory, isNew: '1' })
                .then((res: any) => {
                    const item = res && res.list[0];
                    if (item) {
                        this.amount.successAmount = item.successAmount;
                        this.amount.errorAmount = item.errorAmount;
                        this.amount.totalAmount = item.totalAmount;
                        resolve(item.batchId || '');
                    }
                })
                .catch(err => {
                    reject(err);
                });
        });
    }

    codeFilter: any[] = [];
    nameFilter: any[] = [];
    // 试算结果表筛选
    handleFilterChange(filterList, type) {
        console.log(filterList, 'filterList');
        if (type == 'success') {
            const { code, name } = this.getFilterCodeAndName(filterList);
            this.codeFilter[1] = code;
            this.nameFilter[1] = name;
            this.pagingSuccess.currentPage = 1;
            this.pageChange('success');
        } else {
            const { code, name } = this.getFilterCodeAndName(filterList);
            this.codeFilter[0] = code;
            this.nameFilter[0] = name;
            this.pagingError.currentPage = 1;
            this.pageChange('error');
        }
    }

    getFilterCodeAndName(data) {
        const code = (data.find(item => item.property == 'code') || {}).datas || '';
        const name = (data.find(item => item.property == 'name') || {}).datas || '';
        return { code: code && code[0], name: name && name[0] };
    }

    // 查询点击
    query() {}
}
</script>
<style lang="scss" scoped>
/deep/ .el-table td,
/deep/ .el-table th {
    padding: 5px 0;
}
.content {
    &:nth-child(1) {
        border-right: 1px solid rgb(202, 202, 202);
    }

    .content-header {
        margin-left: 8px;
        height: 30px;
        line-height: 28px;
        padding: 3px;
    }
    .table-height {
        margin: 2px 8px;
        height: calc(100% - 90px) !important;
    }
}
.inner-content {
    height: calc(100vh - 220px);
}
.outer-content {
    height: calc(100vh - 170px);
}
</style>
